package com.example.wxordersystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.wxordersystem.dto.CartDTO;
import com.example.wxordersystem.dto.OrderDTO;
import com.example.wxordersystem.entity.OrderDetail;
import com.example.wxordersystem.entity.OrderMaster;
import com.example.wxordersystem.entity.ProductInfo;
import com.example.wxordersystem.enums.OrderStatusEnum;
import com.example.wxordersystem.enums.PayStatusEnum;
import com.example.wxordersystem.enums.ResultEnum;
import com.example.wxordersystem.exception.SellException;
import com.example.wxordersystem.mapper.OrderDetailMapper;
import com.example.wxordersystem.mapper.OrderMasterMapper;
import com.example.wxordersystem.service.OrderService;
import com.example.wxordersystem.service.ProductService;
import com.example.wxordersystem.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 常红伟
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    ProductService productService;
    /**
     * 用来向订单详情表添加数据
     */
    @Autowired
    OrderDetailMapper orderDetailMapper;
    /**
     * 用来向订单表增加数据
     */
    @Autowired
    OrderMasterMapper orderMasterMapper;


    @Override
    @Transactional(rollbackFor=Exception.class)
    public OrderDTO create(OrderDTO orderDTO) {
        //生成订单ID
        String orderId = KeyUtil.genUniqueKey();
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);
        List<CartDTO> cartDTOList = new ArrayList<>();

        //查询商品
        for(OrderDetail orderDetail : orderDTO.getOrderDetailList()){
            //根据订单里面商品的ID查询此商品在数据库的信息
           ProductInfo productInfo=productService.findOne(orderDetail.getProductId());
           if(productInfo==null){
               throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
           }
            //计算价格  用从数据库里查询出商品单价的价格去乘以购买商品的个数再累计添加到总价格
            orderAmount=productInfo.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add(orderAmount);
           //订单详情入库
            orderDetail.setOrderId(orderId);
            orderDetail.setDetailId(KeyUtil.genUniqueKey());
            BeanUtils.copyProperties(productInfo,orderDetail);
            orderDetailMapper.insert(orderDetail);

            //组建购物车  删减库存也在这一步添加数据
            CartDTO cartDTO =new CartDTO(orderDetail.getProductId(),orderDetail.getProductQuantity());
            cartDTOList.add(cartDTO);

        }
        //写入订单数据库
        OrderMaster orderMaster = new OrderMaster();

        BeanUtils.copyProperties(orderDTO,orderMaster);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderId(orderId);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIL.getCode());
        int i=orderMasterMapper.insert(orderMaster);
        System.out.println("存入成功"+i);

        //执行扣库存操作
        productService.decreaseStork(cartDTOList);
        orderDTO.setOrderId(orderId);
        return orderDTO;
    }

    @Override
    public OrderDTO findOne(String orderId) {
        OrderMaster orderMaster=orderMasterMapper.selectById(orderId);
        if (orderMaster==null){
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        List<OrderDetail> orderDetailList = new ArrayList<>();
        orderDetailList = orderDetailMapper.findByOrderId(orderMaster.getOrderId());
        if (orderDetailList == null){
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setOrderDetailList(orderDetailList);
        BeanUtils.copyProperties(orderMaster,orderDTO);
        return orderDTO;
    }

    @Override
    public List<OrderDTO> findList(String buyerOpenid, int pageNumber, int pageSize) {
       //分页的条件 查询pageNumber页   显示多少pageSize
        Page<OrderMaster> orderMasterPage = new Page<OrderMaster>(pageNumber,pageSize);
        //条件构造器
        QueryWrapper<OrderMaster> orderMasterQueryWrapper = new QueryWrapper<OrderMaster>();
        //查询条件  列buyer_openid  值等于  buyerOpenid
        orderMasterQueryWrapper.eq("buyer_openid",buyerOpenid);
        //返回符合数据的列表
        orderMasterMapper.selectPage(orderMasterPage,orderMasterQueryWrapper);

        List<OrderDTO> orderDTOList = new ArrayList<>();
        for (OrderMaster orderMaster:orderMasterPage.getRecords()){
            OrderDTO orderDTO = new OrderDTO();
            orderDTO.setBuyerOpenid(buyerOpenid);
            BeanUtils.copyProperties(orderMaster,orderDTO);
            orderDTOList.add(orderDTO);
        }
        return orderDTOList;
    }

    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {
        OrderMaster orderMaster = new OrderMaster();
        orderMaster=orderMasterMapper.selectById(orderDTO.getOrderId());
        //如果orderMaster为空 则订单不存
        if (orderMaster==null){
            log.error("【取消订单】订单状态不正确，orderMaster={null}");
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }

        //如果订单状态不是新订单 则抛出异常
       if(!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
           log.error("【取消订单】订单状态不正确，orderId={},orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
           throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
       }

       //修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        Integer result =orderMasterMapper.updateById(orderMaster);
        if (result==0){
            log.error("【取消订单】更新失败，orderMaster={}",orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        //修改库存状态
        List<CartDTO> cartDTOList = new ArrayList<>();
        for (OrderDetail orderDetail:orderDTO.getOrderDetailList()){
            Integer productQuantity =orderDetail.getProductQuantity();
            CartDTO cartDTO = new CartDTO(orderDetail.getProductId(),productQuantity);
            cartDTOList.add(cartDTO);
        }
        productService.increaseStock(cartDTOList);

        //如果已经支付，需要退款
        //TODO

        return orderDTO;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public OrderDTO finish(OrderDTO orderDTO) {

        //判断订单状态
        if(orderDTO.getPayStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.error("【完结订单】订单状态不正确，orderId={},orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO,orderMaster);
        int result =orderMasterMapper.updateById(orderMaster);
        if (result==0){
            log.error("【完结订单】更新失败，orderMaster={}",orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        //推送微信模板消息
        //TODO

        return orderDTO;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public OrderDTO paid(OrderDTO orderDTO) {

        //判断订单支付状态
        if(orderDTO.getPayStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.error("订单支付完成】订单状态不正确，orderId={},orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //判断订单支付状态
        if(orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())){
            log.error("【订单支付完成】订单状态不正确，orderDTO={}",orderDTO);
        }

        //修改订支付状态
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO,orderMaster);
        int result=orderMasterMapper.updateById(orderMaster);
        if (result==0){
            log.error("【完结订单】更新失败，orderMaster={}",orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        return orderDTO;
    }

    @Override
    public List<OrderDTO> findList(int pageNumber, int pageSize) {

       List<OrderMaster>masterList=orderMasterMapper.selectList(null);
       List<OrderDTO> orderDTOList =new ArrayList<>();
       for (OrderMaster orderMaster:masterList){
           OrderDTO orderDTO = new OrderDTO();
           BeanUtils.copyProperties(orderMaster,orderDTO);
           orderDTOList.add(orderDTO);
       }

        return orderDTOList;
    }

}
